package spm.gui;
/* Copyright (C) 2011, Zachary Scott <cthug.zs@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.*;
import javax.swing.*;

import spm.Config;
import spm.format.*;
import static spm.gui.Util.*;

/**
 * Main window frame for the SPM GUI.
 * 
 * @author Zachary Scott <cthug.zs@gmail.com>
 */
public final class PrimaryFrame extends JFrame {

    private final static Logger logger = Logger.getLogger(PrimaryFrame.class.getName());
    
    // package encapsulated by this PrimaryFrame
    private static SPMPackage packageArchive = null;
    
    /** 
     * Creates new PrimaryFrame. 
     *
     * @param packageFile the package file to be opened.
     */
    public PrimaryFrame(final File packageFile) {
        
        initComponents();
        
        // centre the frame of the display
        setLocationRelativeTo(null);
        
        // prime interface
        if (packageFile != null)
            openPackage(packageFile);
        updateValues();
        
    }
    
    /** 
     * Creates new PrimaryFrame. 
     *
     * @param packageFile name of the package to be opened.
     */
    public PrimaryFrame(final String packageFile) {
        
        this(new File(packageFile));
        
    }
    
    /** 
     * Creates new PrimaryFrame. 
     *
     */
    public PrimaryFrame() {
        
        this((File) null);
        
    }
    
    /**
     * Creates a new instance of {@code PrimaryFrame} and starts it in its own thread.
     * 
     * @param packageFile location of the package to be opened in the frame (can be {@code null}).
     * @return the new {@code PrimaryFrame} instance.
     */
    public static PrimaryFrame startNewInstance(final File packageFile) {
        
        final PrimaryFrame frame = new PrimaryFrame(packageFile);
        
        // start new frame instance in its own thread
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                frame.setVisible(true);
            }

        });

        return frame;
        
    }
    
    /**
     * Creates a new instance of {@code PrimaryFrame} and starts it in its own thread.
     * 
     * @param packageFilename location of the package to be opened in the frame (can be {@code null}).
     * @return the new {@code PrimaryFrame} instance.
     */
    public static PrimaryFrame startNewInstance(final String packageFilename) {
        
        if (packageFilename == null) {
            return startNewInstance((File) null);
        } else {
            return startNewInstance(new File(packageFilename));
        }
        
    }

    // updates the value on the frame to those in the package
    private void updateValues() {
        
        // handle null package
        if (packageArchive == null || packageArchive.isEmpty()) { 
            
            // disable install interface
            txtPackage.setEnabled(false);
            txtLicense.setEnabled(false);
            btnInstall.setEnabled(false);
            chkAccept.setEnabled(false);
            // package menu items
            mitemInstall.setEnabled(false);
            mitemUpdate.setEnabled(false);
            mitemUninstall.setEnabled(false);
            
            txtPackage.setText("");
            txtLicense.setText("");
            
        } else { // set package values
            
            // enable install interface
            txtPackage.setEnabled(true);
            txtLicense.setEnabled(true);
            btnInstall.setEnabled(true);
            chkAccept.setEnabled(true);
            // package menu items
            mitemInstall.setEnabled(true);
            mitemUpdate.setEnabled(true);
            mitemUninstall.setEnabled(true);
            
            txtPackage.setText(packageArchive.getName());
            
            txtLicense.setText(packageArchive.getLicenseString());
            txtLicense.setCaretPosition(0);
            
        }
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtPackage = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLicense = new javax.swing.JTextArea();
        btnCancel = new javax.swing.JButton();
        btnInstall = new javax.swing.JButton();
        chkAccept = new javax.swing.JCheckBox();
        menu = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        mitemNewWindow = new javax.swing.JMenuItem();
        mitemOpen = new javax.swing.JMenuItem();
        sep1 = new javax.swing.JPopupMenu.Separator();
        mitemQuit = new javax.swing.JMenuItem();
        menuPackage = new javax.swing.JMenu();
        mitemInstall = new javax.swing.JMenuItem();
        mitemUpdate = new javax.swing.JMenuItem();
        mitemUninstall = new javax.swing.JMenuItem();
        menuHelp = new javax.swing.JMenu();
        mitemOnlineHelp = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        sep2 = new javax.swing.JPopupMenu.Separator();
        mitemAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Simple Package Manager");

        txtPackage.setEditable(false);
        txtPackage.setToolTipText("The currently selected package.");

        jScrollPane1.setFont(new java.awt.Font("Liberation Mono", 0, 13));

        txtLicense.setColumns(72);
        txtLicense.setEditable(false);
        txtLicense.setFont(new java.awt.Font("Liberation Mono", 0, 13)); // NOI18N
        txtLicense.setRows(5);
        jScrollPane1.setViewportView(txtLicense);

        btnCancel.setMnemonic('C');
        btnCancel.setText("Cancel");
        btnCancel.setToolTipText("Cancel installation of the package and close the program");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnInstall.setMnemonic('I');
        btnInstall.setText("Install");
        btnInstall.setToolTipText("Install the package to the system");
        btnInstall.setEnabled(false);
        btnInstall.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                installActionPerformed(evt);
            }
        });

        chkAccept.setText("I have read and accept the above terms and conditions");
        chkAccept.setToolTipText("");
        chkAccept.setEnabled(false);

        menuFile.setMnemonic('F');
        menuFile.setText("File");
        menuFile.setToolTipText("File operations");

        mitemNewWindow.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mitemNewWindow.setMnemonic('F');
        mitemNewWindow.setText("New Window");
        mitemNewWindow.setToolTipText("Starts a new frame.");
        mitemNewWindow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newWindowActionPerformed(evt);
            }
        });
        menuFile.add(mitemNewWindow);

        mitemOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        mitemOpen.setMnemonic('O');
        mitemOpen.setText("Open");
        mitemOpen.setToolTipText("Open a new package from disk");
        mitemOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        menuFile.add(mitemOpen);
        menuFile.add(sep1);

        mitemQuit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mitemQuit.setMnemonic('Q');
        mitemQuit.setText("Quit");
        mitemQuit.setToolTipText("Quit SPM");
        menuFile.add(mitemQuit);

        menu.add(menuFile);

        menuPackage.setMnemonic('P');
        menuPackage.setText("Package");
        menuPackage.setToolTipText("Package operations");
        menuPackage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                installActionPerformed(evt);
            }
        });

        mitemInstall.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        mitemInstall.setMnemonic('I');
        mitemInstall.setText("Install");
        mitemInstall.setToolTipText("Install the package to the system");
        mitemInstall.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                installActionPerformed(evt);
            }
        });
        menuPackage.add(mitemInstall);

        mitemUpdate.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F6, 0));
        mitemUpdate.setMnemonic('U');
        mitemUpdate.setText("Update");
        mitemUpdate.setToolTipText("Update package");
        mitemUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateActionPerformed(evt);
            }
        });
        menuPackage.add(mitemUpdate);

        mitemUninstall.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mitemUninstall.setMnemonic('n');
        mitemUninstall.setText("Uninstall");
        mitemUninstall.setToolTipText("Remove the package from the system");
        mitemUninstall.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uninstallActionPerformed(evt);
            }
        });
        menuPackage.add(mitemUninstall);

        menu.add(menuPackage);

        menuHelp.setMnemonic('H');
        menuHelp.setText("Help");
        menuHelp.setToolTipText("Help information");

        mitemOnlineHelp.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        mitemOnlineHelp.setMnemonic('H');
        mitemOnlineHelp.setText("Online Help");
        mitemOnlineHelp.setToolTipText("View the help information on SPM's website");
        mitemOnlineHelp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mitemOnlineHelpActionPerformed(evt);
            }
        });
        menuHelp.add(mitemOnlineHelp);

        jMenuItem1.setText("Home Page");
        jMenuItem1.setToolTipText("Visit the Simple Package Managers homepage.");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        menuHelp.add(jMenuItem1);
        menuHelp.add(sep2);

        mitemAbout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mitemAbout.setMnemonic('A');
        mitemAbout.setText("About");
        mitemAbout.setToolTipText("View information about SPM");
        mitemAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mitemAboutActionPerformed(evt);
            }
        });
        menuHelp.add(mitemAbout);

        menu.add(menuHelp);

        setJMenuBar(menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(txtPackage, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chkAccept)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 127, Short.MAX_VALUE)
                .addComponent(btnInstall)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancel)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(txtPackage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(chkAccept)
                    .addComponent(btnCancel)
                    .addComponent(btnInstall))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    /**
     * Opens the given package in the frame.
     * 
     * @param file location of the package to be opened.
     */
    public void openPackage(final File file) {
        
        if (file == null)
            throw new NullPointerException();
        
        packageArchive = null;
        
        // read the package archive
        SPMPackage archive = new SPMPackage();
        Thread readThread = archive.newReadThread(file);
        readThread.start();

        // display a loading dialog while the package is read
        showLoadingDialog(this, readThread, "Loading " + file.getName());

        // update the package that this frame represents
        packageArchive = archive;
        updateValues();
        
    }
    
    /**
     * Opens the given package in the frame.
     * 
     * @param filname location of the package to be opened.
     */
    public void openPackage(final String filename) {
        openPackage(new File(filename));
    }
    
    private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
        
        // prompt user to open a file
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(this);
 
        // open selected file
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            
            openPackage(chooser.getSelectedFile());
            
        }
        
    }//GEN-LAST:event_openActionPerformed

    // install the package
    private void installActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_installActionPerformed
        
        if (chkAccept.isSelected()) {
            
            if (packageArchive != null) {
                RunDialog run = new RunDialog(this, packageArchive);
                run.install();
            }
        
        } else {
            
            showWarningDialog(this, 
                              "You must accept the license terms and conditions to install the package!");
            
        }
            
    }//GEN-LAST:event_installActionPerformed

    // update the package
    private void updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateActionPerformed
        
        if (chkAccept.isSelected()) {
            
            if (packageArchive != null) {
                RunDialog run = new RunDialog(this, packageArchive);
                run.update();
            }
        
        } else {
            
            showWarningDialog(this, 
                              "You must accept the license terms and conditions to update the package!");
            
        }
        
    }//GEN-LAST:event_updateActionPerformed

    // uninstall the package
    private void uninstallActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uninstallActionPerformed
        
        if (packageArchive != null) {
            RunDialog run = new RunDialog(this, packageArchive);
            run.uninstall();
        }
        
    }//GEN-LAST:event_uninstallActionPerformed

    // open a new primary frame
    private void newWindowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newWindowActionPerformed
        startNewInstance((File) null);
    }//GEN-LAST:event_newWindowActionPerformed

    // close window
    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void mitemOnlineHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mitemOnlineHelpActionPerformed
        Util.showInWebBrowser(this, Config.WIKI_URI);
    }//GEN-LAST:event_mitemOnlineHelpActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        Util.showInWebBrowser(this, Config.HOMEPAGE_URI);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void mitemAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mitemAboutActionPerformed
        AboutDialog aboutDialog = new AboutDialog(this);
        aboutDialog.setVisible(true);
    }//GEN-LAST:event_mitemAboutActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnInstall;
    private javax.swing.JCheckBox chkAccept;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuBar menu;
    private javax.swing.JMenu menuFile;
    private javax.swing.JMenu menuHelp;
    private javax.swing.JMenu menuPackage;
    private javax.swing.JMenuItem mitemAbout;
    private javax.swing.JMenuItem mitemInstall;
    private javax.swing.JMenuItem mitemNewWindow;
    private javax.swing.JMenuItem mitemOnlineHelp;
    private javax.swing.JMenuItem mitemOpen;
    private javax.swing.JMenuItem mitemQuit;
    private javax.swing.JMenuItem mitemUninstall;
    private javax.swing.JMenuItem mitemUpdate;
    private javax.swing.JPopupMenu.Separator sep1;
    private javax.swing.JPopupMenu.Separator sep2;
    private javax.swing.JTextArea txtLicense;
    private javax.swing.JTextField txtPackage;
    // End of variables declaration//GEN-END:variables

}

// EOF
